<?php

namespace app\jigou\controller\qingdongams\workorder;

use addons\qingdongams\model\AftermarketType;
use addons\qingdongams\model\Comment;
use addons\qingdongams\model\Companys;
use addons\qingdongams\model\Consume;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\Customer as CustomerModel;
use addons\qingdongams\model\Equipment;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\File;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\OperationLog;
use addons\qingdongams\model\Product;
use addons\qingdongams\model\StaffSignIn;
use addons\qingdongams\model\WorkorderLogistics;
use addons\qingdongams\model\WorkorderProgress;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\CustomerProduct;
use addons\qingdongams\model\Workorder as WorkorderModel;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Contacts;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 工单管理
 * @icon fa fa-user
 */
class Workorder extends Base
{
    protected $relationSearch = true;
    protected $searchFields   = 'id,workorder_number,title';
    /**
     * @var \addons\qingdongams\model\Workorder
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WorkorderModel();
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $need = input('need','','trim');
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $createtime = input('createtime','');
            $wheres = [];
            if($need && $need =='workorder'){
                $wheres['status'] = 1;
            }
            if($createtime && $createtime !='null '){
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
                $wheres['createtime'] = array('between',array(strtotime($start),strtotime($end)));
            }
            $whereStaff = function ($query) {
                $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                    ->whereOr('', 'exp', "FIND_IN_SET({$this->_staff->id},show_staff_id)");
            };
            $list = $this->model->where($where)->where($wheres)->where($whereStaff)->with(['customer', 'contacts'])->order('id desc')->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }

    //新增
    public function add()
    {
        $workorder_type = input('workorder_type');

        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if(isset($params['product'])){
                if (!$params['product'] || $params['product'] =='[]') {
                    $this->error('请选择产品');
                }
            }else if(isset($params['customer_product_id'])){
                if (!$params['customer_product_id'] || $params['customer_product_id'] =='[]') {
                    $this->error('请选择产品');
                }
            }else if(isset($params['product_part'])){
                if (!$params['product_part'] || $params['product_part'] =='[]') {
                    $this->error('请选择产品');
                }
            }

            // 表单验证
            if (($result = $this->validate($params, 'addons\qingdongams\validate\Workorder.create')) !== true) {
                $this->error($result);
            }
            if (WorkorderModel::where([
                'workorder_number' => $params['workorder_number'],
            ])->find()) {
                $this->error('工单编号已存在');
            }
            try {
                if (isset($params['files'])) {
                    $params['files'] = File::getId($params['files']);
                }
                if (isset($params['file_ids'])) {
                    $params['file_ids'] = File::getId($params['file_ids']);
                }
                if (isset($params['product'])) {
                    $params['product'] = json_decode($params['product'], true);
                }
                if (isset($params['parts'])) {
                    $params['parts'] = json_decode($params['parts'], true);
                }
                if (isset($params['customer_product_id'])) {
                    $params['customer_product_id'] = json_decode($params['customer_product_id'], true);
                    $customer_product_id = [];
                    foreach ($params['customer_product_id'] as $v) {
                        $customer_product_id[] = $v['customer_product_id'];
                    }
                    $params['customer_product_id'] = implode(',', $customer_product_id);
                }
                if (isset($params['product_part'])) {
                    $params['product_part'] = json_decode($params['product_part'], true);
                    $customer_product_id = [];
                    foreach ($params['product_part'] as $v){
                        $customer_product_id[] = $v['customer_product_id'];
                    }
                    $params['customer_product_id'] = implode(',', $customer_product_id);
                }
                $result = WorkorderModel::createWorkorder($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('添加工单成功');
            }
        }
        $this->assign('workorder_type', $workorder_type);
        $this->assign('number', getItemNumber('workorder'));
        $this->assign('staffs', Staff::getList());
        $template = 'qingdongams/workorder/workorder/add_template/';
        if ($workorder_type == '设计工单') {
            return $this->view->fetch($template . 'add');
        } elseif ($workorder_type == '生产工单') {
            return $this->view->fetch($template . 'add1');
        } elseif ($workorder_type == '产品发货') {
            return $this->view->fetch($template . 'add2');
        } elseif ($workorder_type=='上门安装') {
            return $this->view->fetch($template . 'add3');
        } elseif ($workorder_type == '上门维修') {
            $all = AftermarketType::where([])->select();
            $all = collection($all)->toArray();
            $tree = Tree::instance()->init($all, 'pid');
            $aftermarket_type = $tree->getTree(0, "<option value=@id @selected @disabled>@spacer@name</option>", '', '15,17');
            $this->assign('aftermarket_type', $aftermarket_type);

            return $this->view->fetch($template . 'add4');
        } elseif ($workorder_type == '返厂维修') {
            return $this->view->fetch($template . 'add5');
        } elseif ($workorder_type == '品质异常单') {
            return $this->view->fetch($template . 'add6');
        } elseif ($workorder_type == '电话售后') {
            return $this->view->fetch($template . 'add7');
        }
    }

    //编辑
    public function edit($ids=null)
    {

        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if(isset($params['product'])){
                if (!$params['product'] || $params['product'] =='[]') {
                    $this->error('请选择产品');
                }
            }else if(isset($params['customer_product_id'])){
                if (!$params['customer_product_id'] || $params['customer_product_id'] =='[]') {
                    $this->error('请选择产品');
                }
            }else if(isset($params['product_part'])){
                if (!$params['product_part'] || $params['product_part'] =='[]') {
                    $this->error('请选择产品');
                }
            }

            // 表单验证
            if (($result = $this->validate($params, 'addons\qingdongams\validate\Workorder.create')) !== true) {
                $this->error($result);
            }
            try {
                if (isset($params['file_ids'])) {
                    $params['file_ids'] = File::getId($params['file_ids']);
                }
                if (isset($params['files'])) {
                    $params['files'] = File::getId($params['files']);
                }
                if (isset($params['product'])) {
                    $params['product'] = json_decode($params['product'], true);
                }
                if (isset($params['product_part'])) {
                    $params['product_part'] = json_decode($params['product_part'], true);
                }
                if (isset($params['parts'])) {
                    $params['parts'] = json_decode($params['parts'], true);
                }
                if (isset($params['customer_product_id'])) {
                    $params['customer_product_id'] = json_decode($params['customer_product_id'], true);
                    $customer_product_id = [];
                    foreach ($params['customer_product_id'] as $v) {
                        $customer_product_id[] = $v['customer_product_id'];
                    }
                    $params['customer_product_id'] = implode(',', $customer_product_id);
                }
                $result = WorkorderModel::updateWorkorder($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('编辑工单成功');
            }
        }
        // 基本信息
        $workorder = WorkorderModel::where(['id' => $ids])->with(['createStaff',
            'contacts', 'customer', 'ownerStaff', 'file', 'getevent', 'visit'])->find();
        if (empty($workorder)) {
            $this->error('工单不存在');
        }
        $workorder = $workorder->toArray();
        $workorder['customer_product_id']=explode(',',$workorder['customer_product_id']);
        $customer_product=[];
        foreach ($workorder['customer_product_id'] as $pid){
            $cp=CustomerProduct::where(['id'=>$pid])->with(['product'])->find();
            $cp['customer_product_id']=$pid;
            $customer_product[]=$cp;
        }
        $workorder['customer_product']= $customer_product;
        $files=[];
        foreach ($workorder['file'] as $f) {
            $files[] = $f['file_path'];
        }
        if($workorder['product_part']){
            $product_part=[];
            foreach ($workorder['product_part'] as $v){

                $v['customer_product_id']=$v['id'];
                $product_part[]=$v;
            }
            $workorder['product_part']=$product_part;
        }
        $workorder['files']=implode(',',$files);
        $workorder_type=$workorder['workorder_type'];
        $this->assign('row', $workorder);
        $this->assign('workorder_type', $workorder_type);
        $this->assign('staffs', Staff::getList());
        $template = 'qingdongams/workorder/workorder/edit_template/';
        if ($workorder_type == '设计工单') {
            return $this->view->fetch($template . 'edit');
        } elseif ($workorder_type == '生产工单') {
            return $this->view->fetch($template . 'edit1');
        } elseif ($workorder_type == '产品发货') {
            return $this->view->fetch($template . 'edit2');
        } elseif ($workorder_type == '上门安装') {
            return $this->view->fetch($template . 'edit3');
        } elseif ($workorder_type == '上门维修') {
            $all = AftermarketType::where([])->select();
            $aftermarket_type_ids=$workorder['aftermarket_type_ids'];
            $all = collection($all)->toArray();
            $tree = Tree::instance()->init($all, 'pid');
            $aftermarket_type = $tree->getTree(0, "<option value=@id @selected @disabled>@spacer@name</option>", $aftermarket_type_ids, '15,17');
            $this->assign('aftermarket_type', $aftermarket_type);

            return $this->view->fetch($template . 'edit4');
        } elseif ($workorder_type == '返厂维修') {
            return $this->view->fetch($template . 'edit5');
        } elseif ($workorder_type == '品质异常单') {
            return $this->view->fetch($template . 'edit6');
        } elseif ($workorder_type == '电话售后') {
            return $this->view->fetch($template . 'edit7');
        }
    }

    /**
     * 搜索下拉列表
     */
    public function stafflist()
    {

        $data = ['searchlist' => Staff::getList()];
        $this->success('', null, $data);
    }

    //工单详情
    public function detail($ids = null)
    {
        $types = input('types','workorder');
        // 基本信息
        $workorder = WorkorderModel::where(['id' => $ids])->with(['createStaff',
            'contacts', 'customer', 'ownerStaff', 'file', 'getevent', 'visit','createPerson'])->find();
        if (empty($workorder)) {
            $this->error('工单不存在');
        }
        $workorder = $workorder->toArray();
        if (empty($workorder)) {
            $this->error('信息不存在');
        }
        if (!in_array($this->_staff->id, explode(',', $workorder['show_staff_id']))
            && !in_array($workorder['owner_staff_id'], Staff::getLowerStaffId()) && $this->_staff->id != $workorder['create_staff_id']) {
         //   $this->error('权限不足，无法查看工单','',403);
        }
        Message::setRead($types, $ids, $this->_staff->id);
        if ($workorder['check_status'] == 1) {//审核中
            $workorder['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::WORKORDER_TYPE, $ids);
        } else {
            $workorder['is_examine'] = 0;
        }
        if (empty($workorder['contacts'])) {
            $workorder['contacts'] = Contacts::where(['customer_id' => $workorder['customer_id']])->order('is_major desc')->field('id,customer_id,name,mobile,mobilecode,region')->find();

        }
        if ($workorder['aftermarket_type_ids']) {
            $names = AftermarketType::where(['id' => ['in', explode(',', $workorder['aftermarket_type_ids'])]])->column('name');
            $workorder['aftermarket_type_ids'] = implode(',', $names);
        }
        $workorder['is_revoke'] = 0;//是否可以撤销
        $workorder['is_operation'] = 0;//是否可以操作
        $workorder['is_operation_visit'] = 0;//操作回访
        $workorder['is_financial'] = 0;//是否财务审核
        $workorder['is_leader'] = 0;//是否可以录入费用
        if ($workorder['create_staff_id'] == $this->_staff->id || in_array($workorder['create_staff_id'], Staff::getLowerStaffId()) ) {
            //是否可以撤销
            $workorder['is_revoke'] = 1;
        }
        //领导录入费用和回款

        //是否可以录入费用-是否可以回款
        $workorder['is_leader'] = 1;
        if (in_array($workorder['workorder_type'], ['产品发货', '设计工单'])) {
            //业务部领导可以操作发货工单 和 发货工单
            $workorder['is_leader'] = 1;
        }
        if ($workorder['owner_staff_id'] == $this->_staff->id) {
            //是否可以操作
            $workorder['is_operation'] = 1;
        }
        //操作回访
        $workorder['is_operation_visit'] = 1;

        if ($workorder['status'] == 3 && $workorder['is_pay'] == 1 && $workorder['is_financial_audit'] == 0 ) {
            //是否财务审核
            $workorder['is_financial'] = 1;
        }
        //是否可以操作物流
        $workorder['is_operation_logistics'] = 0;
        if ($workorder['customer_product_id']) {
            $customer_product_ids = explode(',', $workorder['customer_product_id']);
            $workorder['customer_product'] = CustomerProduct::where(['id' => ['in', $customer_product_ids]])->with(['product'])->select();
            $workorder['customer_product'] = collection($workorder['customer_product'])->toArray();

            foreach ($workorder['customer_product'] as $k => $v) {
                if ($v['number'] && $v['status'] == '待发货') {
                    $workorder['is_operation_logistics'] = 1;
                }
            }
        }

        if ($workorder['workorder_type'] == '上门维修' || $workorder['workorder_type'] == '返厂维修') {
            $workorder['peisong'] = WorkorderModel::where(['relation_workorder_id' => $ids,
                'workorder_type' => '配件配送'])->select();
            $workorder['anzhuang'] = WorkorderModel::where(['relation_workorder_id' => $ids,
                'workorder_type' => '配件安装'])->select();

        }
        if ($workorder['flow_staff_ids']) {
            $workorder['flow_staff'] = Staff::where(['id' => ['in', $workorder['flow_staff_ids']]])->field('id,name,img')->select();
        }

        //是否可以操作完成
        $workorder['is_operation_end'] = 0;
        if (in_array($workorder['status'], [0, 1])) {
            $workorder['is_operation_end'] = 1;
        }
        // 跟进记录
        $where = [
            'relation_type' => 'workorder',
            'relation_id' => $ids,
        ];
        $records = StaffSignIn::where($where)->with([
            'staff'
        ])->order('id desc')->select();
        $this->assign('records', $records);

        // 物流信息
        $logistics = WorkorderLogistics::where('workorder_id', $ids)->select();
        if ($logistics) {
            $logistics = collection($logistics)->toArray();
            foreach ($logistics as $k => $v) {
                $v['content'] = $v['content'] ?: [];
                $v['content'] = array_reverse($v['content']);
                if ($v['company']) {
                    $v['company'] = Companys::where(['no' => $v['company']])->value('com');
                }
                $logistics[$k] = $v;
            }
        }
        //
        $model = new WorkorderProgress();
        $staffsProgress = $model->where(['workorder_id' => $ids])->with(['createStaff'])->select();

        $this->assign('staffsProgress',$staffsProgress);

        $where = [];
        $where['relation_type'] = 'workorder';
        $where['relation_id'] = $ids;
        $where['type'] = 4;//协作任务
        $assist_task = Event::where($where)->with([
            'staff',
            'customer',
            'comments',
        ])->order('id desc')->select();
        $assist_task = collection($assist_task)->toArray();


        $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::WORKORDER_TYPE,$ids));
        $this->assign('flow',Flow::getstepdetail(Flow::WORKORDER_STATUS, $ids));

        $this->assign('assist_task', $assist_task);
        $this->assign('logistics', $logistics);
        // 操作记录
        $operations = OperationLog::getList(OperationLog::WORKORDER_TYPE, $ids);

        $this->assign('operations', $operations);

        $this->view->assign('row', $workorder);
        $this->view->assign('ids', $ids);
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }

    //获取费用
    public function get_consume($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list   = Consume::where([
            'relation_type' => 'workorder',
            'relation_id' => $ids,
        ])->with(['staff'])->order('id desc')->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }


    //转派工单
    public function transfer($ids = null)
    {
        if ($this->request->isAjax()) {
            $id = input('id');
            $staff_id = input('staff_id');
            $desc = input('desc');
            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            if ($row['owner_staff_id'] == $staff_id) {
                $this->error('不能将工单转派给原负责人');
            }

            Db::startTrans();
            try {
                WorkorderModel::transferWorkorder($id, $staff_id, $desc);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('转派成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //回执工单
    public function receipt($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if (empty($params['id'])) {
                $this->error('id不能为空');
            }
            if (empty($params['receipt_file_ids'])) {
                $this->error('回执单不能为空');
            }
            if (empty($params['receipt_date'])) {
                $this->error('回执时间不能为空');
            }

            Db::startTrans();
            try {
                $result = WorkorderModel::receiptWorkorder($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('回执成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //添加跟进记录
    public function add_log($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if (empty($params['id']) || empty($params['desc'])) {
                $this->error('参数不能为空');
            }
            if (empty($params['lng']) || empty($params['lat']) || empty($params['location'])) {
//                $this->error('定位地理位置错误');
            }
            $row = WorkorderModel::get($params['id']);
            if (empty($row)) {
                $this->error('工单不存在');
            }
            try {
                $content = $params['desc'];

                $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $params['relation_id'] = $row['id'];
                //创建跟进记录
                StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('添加工单备注成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //接受工单
    public function accept_order($ids=null)
    {
        $params = $this->request->post();
        if(!$ids){
            $params['id'] = isset($params['id']) ? $params['id'] : '';
        }else{
            $params['id'] = $ids;
        }
        if (empty($params['id'])) {
            $this->error('参数不能为空');
        }
        $row = WorkorderModel::where(['id' => $params['id']])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        Db::startTrans();
        try {
            $params['workorder_type'] = $row['workorder_type'];
            WorkorderModel::acceptWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('接受工单成功');
    }

    //设置产品编号
    public function set_customer_product_number($ids = null)
    {
        if ($this->request->isAjax()) {

            $workorder_id = $ids;
            $params = $this->request->post('row/a');

            try {
                Db::startTrans();
                $product = json_decode($params['product'], true);
                if (!empty($product)) {
                    foreach ($product as $v) {
                        if (empty($v['id']) || empty($v['number'])) {
                            throw new Exception('产品编号不能为空');
                        }
                        $hasBing = CustomerProduct::where(['id' => $v['id']])->find();
                        if (!empty($hasBing['number'])) {
                            $logicStatus = CustomerProduct::alias('c')->where(['number' => $hasBing['number']])->join('qingdongams_workorder w', 'w.customer_product_id=c.id', 'left')->field('w.id,w.process')->find();
                            if ($logicStatus['process'] >= 3) {
                                throw new Exception('产品编号[' . $hasBing['number'] . ']已配送,编号[' . $v['number'] . ']不能配送');
                            }
                            // 如果已经绑定，则原先设备 解绑
                            Equipment::where(['number' => $hasBing['number']])->update(['binding_status' => 1, 'cus_pro_id' => 0]);
                        }
                        CustomerProduct::where(['id' => $v['id']])->update(['number' => $v['number'], 'file_ids' => File::getId($v['file_ids'])]);
                    }
                }
                unset($params['product']);
                $params['workorder_id'] = $params['id'];
                WorkorderModel::setProductNumber($workorder_id, $params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('设置产品编号成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $row['customer_product']='';
        if ($row['customer_product_id']) {
            $customer_product_ids = explode(',', $row['customer_product_id']);
            $row['customer_product'] = CustomerProduct::where(['id' => ['in', $customer_product_ids]])->with(['product'])->select();
            $customer_product = [];
            foreach ($row['customer_product'] as $k => $v) {

                $customer_product[] = [
                    'id' => $v['id'],
                    'product_id' => $v['product_id'],
                    'number' => $v['number'],
                    'file_ids' => implode(',', $v['file_ids']),
                ];
            }
            $row['customer_product'] = json_encode($customer_product);
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //添加物流信息
    public function add_logistics($ids = null)
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post('row/a');
            $workorder_id = $ids;//工单id
            $number = $data['number'];//物流编号
            $senderPhone = $data['sender_phone'];//发货人手机号 后四位
            $receiverPhone = $data['receiver_phone'];//发货人手机号 后四位
            $product_ids = $data['product_ids'] ?? '';//产品id
            $type = $data['type'];//
            $file_ids = $data['file_ids'];
            $company = $data['company'];
            $money = $data['money'];
            if ($type == '物流配送') {
                if (empty($number)) {
                    $this->error('物流编号不能为空');
                }
            }
            $workorder = WorkorderModel::where(['id' => $workorder_id])->find();
            if (empty($workorder)) {
                $this->error('工单不能为空');
            }
            $params = [
                'title' => '',
                'customer_id' => $workorder['customer_id'],
                'workorder_id' => $workorder_id,
                'number' => $number,
                'file_ids' => File::getId($file_ids),
                'company' => $company,
                'type' => $type,
                'money' => $money,
                'receiver_phone' => $senderPhone,
                'sender_phone' => $receiverPhone,
                'product_ids' => $product_ids,
                'current_status' => json_encode(['text' => date('m-d H:i'), 'desc' => '提交物流信息'], JSON_UNESCAPED_UNICODE),
                'content' => json_encode([['text' => date('m-d H:i'), 'desc' => '提交物流信息']], JSON_UNESCAPED_UNICODE),
            ];
            $customerInfo = Customer::where(['id' => $workorder['customer_id']])->find();
            try {
                Db::startTrans();
                WorkorderLogistics::createLogistics($params);
                $product_ids = explode(',', $product_ids);
                foreach ($product_ids as $id) {
                    if ($workorder['is_install'] == 1) {
                        if ($workorder['workorder_type'] == '配件配送') {
                            //获取售后助理
                            $addWorkorder = [
                                'workorder_number' => WorkorderModel::getWorkorderNumber(),
                                'workorder_type' => '配件安装',
                                'title' => '配件安装',
                                'customer_id' => $customerInfo['id'],
                                'contacts_id' => $workorder['contacts_id'],
                                'address' => $customerInfo['address'],
                                'address_detail' => $customerInfo['address_detail'],
                                'lng' => $customerInfo['lng'],
                                'lat' => $customerInfo['lat'],
                                'parts' => $workorder['parts'],
                                'priority' => '一般',
                                'owner_staff_id' => $workorder['owner_staff_id'],
                                'desc' => '自动生成安装工单'
                            ];
                            WorkorderModel::createWorkorder($addWorkorder);
                        } else {
                            //获取售后助理
                            $addWorkorder = [
                                'workorder_number' => \addons\qingdongams\model\Workorder::getWorkorderNumber(),
                                'workorder_type' => '上门安装',
                                'title' => '上门安装',
                                'customer_id' => $customerInfo['id'],
                                'contacts_id' => $workorder['contacts_id'],
                                'address' => $customerInfo['address'],
                                'address_detail' => $customerInfo['address_detail'],
                                'lng' => $customerInfo['lng'],
                                'lat' => $customerInfo['lat'],
                                'customer_product_id' => $id,
                                'priority' => '一般',
                                'owner_staff_id' => $workorder['owner_staff_id'],
                                'desc' => '自动生成安装工单'
                            ];
                            WorkorderModel::createWorkorder($addWorkorder);
                        }

                    }
                }

                WorkorderModel::setLogistics($workorder_id, $product_ids);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('添加物流信息成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        if ($row['customer_product_id']) {
            $customer_product_ids = explode(',', $row['customer_product_id']);
            $row['customer_product'] = CustomerProduct::where(['id' => ['in', $customer_product_ids], 'status' => 0])->with(['product'])->select();
            $customer_product = [];
            $product_ids = [];
            foreach ($row['customer_product'] as $k => $v) {
                $product_ids[] = $v['id'];
                $customer_product[] = [
                    'id' => $v['id'],
                    'product_id' => $v['product_id'],
                    'number' => $v['number'],
                    'name' => $v['product']['name'],
                ];
            }
            $row['product_ids'] = implode(',', $product_ids);
            $row['customer_product'] = json_encode($customer_product);
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //修改物流信息
    public function edit_logistics($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $logistics = WorkorderLogistics::where(['id' => $ids])->find();
            if (empty($logistics)) {
                $this->error('物流信息不存在');
            }
            try {
                Db::startTrans();
                $params['file_ids'] = File::getId($params['file_ids']);
                WorkorderLogistics::updateLogistics($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改物流信息成功');
        }
        $logistics = WorkorderLogistics::where(['id' => $ids])->find()->toArray();
        $file_url = [];
        foreach ($logistics['file_ids'] as $file) {
            $file_url[] = $file['url'];
        }
        $logistics['file_ids'] = implode(',', $file_url);
        $this->assign('row', $logistics);
        return $this->view->fetch();
    }

    //完成工单
    public function complete($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $id = $params['id'];
            $desc = $params['desc'] ?? '';
            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            if ($row['is_pause'] == 1) {
                $this->error('工单暂停中');
            }
            if ($params['discount_money'] ?? 0 > 0) {
                if (empty($params['flow_staff_ids'])) {
                    $this->error('工单审批人不能为空');
                }
            }
            Db::startTrans();
            try {
                WorkorderModel::completeWorkorder($id, $desc, $params);
                if ($row['workorder_type'] == '产品发货') {//送达待安装
                    CustomerProduct::where(['id' => ['in', $row['customer_product_id']]])->update([
                        'status' => 2
                    ]);
                }
                //协助任务完成
                Event::where(['relation_type' => 'workorder', 'relation_id' => $row['id'], 'type' => 4])->update(['status' => 2]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('工单完结成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    //电话工单完成
    public function complete_mobile($ids=null){

        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $id = $params['id'];
            $desc = $params['desc'] ?? '';
            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            Db::startTrans();
            try {
                if($params['is_part'] == 1){
                    $params['use_parts']=[];
                }else{
                    $params['use_parts']=json_decode($params['use_parts'],true);
                }
                WorkorderModel::completeWorkorder($id, $desc, $params);
                //协助任务完成
                Event::where(['relation_type' => 'workorder', 'relation_id' => $row['id'], 'type' => 4])->update(['status' => 2]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('工单完结成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    //工单失败
    public function fail_workorder($ids = null)
    {

        if ($this->request->isAjax()) {
            $id = input('id');
            $desc = input('desc');
            //
            $params = $this->request->post();
            if (empty($id)) {
                $this->error('参数错误');
            }
            $workorder = WorkorderModel::get($id);
            if (empty($workorder)) {
                $this->error('信息不存在');
            }
            Db::startTrans();
            try {
                WorkorderModel::failWorkorder($id, $desc);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('提交成功');
        }

        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //协助任务 多条
    public function add_events($ids = null)
    {
        if ($this->request->isAjax()) {
            $data = input('row/a');
            if (empty($data)) {
                $this->error('请添加协助人');
            }
            try {
                $staffIds = [];
                $staffIds[] = $data['staff_id'];
                $params = [
                    'staff_id' => $data['staff_id'] ?? 0,
                    'title' => $data['title'] ?? '协助任务',
                    'remark' => $data['remark'] ?? '',
                    'type' => 4,//协助任务
                    'status' => 1,//
                    'relation_type' => 'workorder',
                    'relation_id' => $data['id'],
                ];
                $result = Event::createEvent($params);

                $row = WorkorderModel::get($data['id']);

                if ($row['status'] == 1) {
                    $update = ['status' => 2];
                    if ($row['workorder_type'] == '设计工单') {
                        $update['process'] = 1;
                    }
                    $row->save($update);
                    Event::where(['relation_type' => 'workorder', 'relation_id' => $data['id'], 'type' => 1])
                        ->update(['status' => 1]);
                }
                $names = Staff::where(['id' => ['in', $staffIds]])->column('name');
                $content = "邀请" . implode(',', $names) . "协作";
                $data['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $data['relation_id'] = $row['id'];
                $data['relation_process'] = '邀请协作';
                //创建跟进记录
                StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('添加协助任务成功');
            }
        }

        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //协助任务评论
    public function assits_comment($ids = null)
    {

        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $relation_type = Comment::ASSIST_EVENT_TYPE;
            if(empty($params['id'])){
                $this->error('评论ID不能为空');
            }
            if(empty($params['content'])){
                $this->error('评论内容不能为空');
            }
            $relation_id = $params['id'];
            $content = $params['content'];
            $files = $params['file_ids']??'';
            $files=File::getId($files);
            $staff = Staff::info();
            Comment::addComment($content, $files, $relation_id, $relation_type, $staff->id);
            $this->success('评论成功');
        }

        // 基本信息
        $row = Event::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('日程不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //填写维修结果
    public function repair_result($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $id = $ids;

            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            Db::startTrans();
            try {
                $params['use_parts'] = json_decode($params['use_parts'], true);
                WorkorderModel::repairResult($id, $params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('提交成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //录入工单费用
    public function enter_workorder_money($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $id = $ids;

            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            Db::startTrans();
            try {
                if ($row['tax'] == 1) {
                    $row['tax'] = "含{$row['tax_num']}%专用增值税发票";
                } else {
                    $row['tax'] = '不含税';
                }
                WorkorderModel::enterWorkorderMoney($id, $params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('提交成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //取消测试/继续测试
    public function is_continue_test()
    {
        $is_continue = input('is_continue');
        $id = input('id');
        Db::startTrans();
        try {
            WorkorderModel::continueTest($id, $is_continue);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }

    //添加品质异常单进度
    public function add_progress($ids = null)
    {

        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params['workorder_id']=$ids;
            $result=WorkorderModel::addProgress($params);
            if($result){
                $this->success('操作成功');
            }
            $this->error('操作失败');
        }

        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //编辑优惠金额
    public function edit_discount_money($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $id = $ids;
            $is_charge = $params['is_charge'];//1 收费     2不收费
            $discount_money = $params['discount_money'] ?? 0;
            $discount_desc = $params['discount_desc'] ?? 0;
            if (empty($id)) {
                $this->error('参数错误');
            }
            $row = WorkorderModel::where(['id' => $id])->find();
            Db::startTrans();
            try {
                $money = sprintf('%.2f', $row['total_money'] - $discount_money);
                $update = [
                    'is_charge' => $is_charge,
                    'discount_money' => $discount_money,
                    'money' => $money,
                    'discount_desc' => $discount_desc
                ];
                //设置产品编号
                WorkorderModel::where(['id' => $id])->update($update);
                if ($is_charge == 2) {

                    $content = '设置工单费用为[不收费]';
                } else {
                    $content = '编辑优惠金额为[' . $discount_money . ']';
                }
                $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
                $params['relation_id'] = $id;
                $params['relation_process'] = '编辑优惠金额';
                //创建跟进记录
                StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改工单信息成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //支付订单 去结算
    public function pay_order($ids = null)
    {
        if ($this->request->isAjax()) {
            $id = $ids;
            $params = $this->request->post('row/a');
            $pay_type = $params['pay_type'] ?? '';
            $pay_files = $params['pay_files'] ?? '';
            if (empty($pay_type)) {
                $this->error('支付类型不能为空');
            }
            if (empty($pay_files)) {
                $this->error('支付凭证不能为空');
            }
            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('订单不存在');
            }
            if ($row['is_pay'] == 1) {
                $this->error('订单已支付');
            }
            $pay_files = File::getId($pay_files);
            $update = ['is_pay' => 1, 'pay_time' => time(), 'pay_type' => $pay_type, 'pay_files' => $pay_files];
            if ($row['workorder_type'] == '返厂维修') {
                $update['process'] = 5;
            } else if (in_array($row['workorder_type'], ['上门维修', '电话售后', '配件安装'])) {
                $update['status'] = 3;
            }
            if ($row['is_pay'] == 1) {
                //发送通知
                Message::addMessage(Message::WORKORDER_TYPE, $id, $row['owner_staff_id'], $this->_staff->id, '《' . $row->title . '》任务已完成，请您及时确认回款情况！');
            }
            $result = WorkorderModel::where(['id' => $id])->update($update);
            if (empty($result)) {
                $this->error('修改信息失败');
            }
            if (isset($update['status']) && $update['status'] == 3) {
                //工单完成
                WorkorderModel::setComplete($id);
            }

            $content = '支付维修费用成功';
            $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
            $params['relation_id'] = $row['id'];
            $params['files'] = $params['files'] ?? '';
            $params['relation_process'] = '支付费用';
            //创建跟进记录
            StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

            $this->success('支付订单成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //关闭工单
    public function cancel_workorder($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $id = $params['id'] ?? 0;
            $desc = $params['desc'] ?? '';
            if (empty($id)) {
                $this->error('id不能为空');
            }
            if (empty($desc)) {
                $this->error('备注不能为空');
            }

            Db::startTrans();
            try {
                WorkorderModel::cancelWorkorder($id, $desc);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('终止成功');
        }
        // 基本信息
        $row = WorkorderModel::where(['id' => $ids])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //获取联合跟进人
    public function getShowStaff($ids = null)
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE, 'relation_id' => $ids])->with(['staff'])->paginate($limit);
        $total = $list->total();
        $stfflist = $list->toArray()['data'];
        foreach ($stfflist as $k => $value){
            if ($value['roles'] == 1){
                $stfflist[$k]['is_edit'] = '负责人';
            }else{
                $stfflist[$k]['is_edit'] = $value['is_edit'] == 1?'读写':'只读';
            }
            $stfflist[$k]['roles'] = $value['roles'] == 1?'负责人':'团队成员';
        }
        $result = array("total" => $total, "rows" => $stfflist);

        return json($result);
    }


    public function set_team($ids = null){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $id = $params['id'];
                $staff = $params['staff'];
                $model = \addons\qingdongams\model\Workorder::get($id);
                if (empty($model)) {
                    $this->error('客户不存在');
                }
                foreach ($staff as $k=>$v) {
                    if ($v['roles'] == 1) {//负责人
                        $find = JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE,
                            'relation_id' => $id,
                            'roles' => 1
                        ])->find();
                        if($v['id'] != $find['staff_id']){
                            \addons\qingdongams\model\Workorder::transfer($id, $v['id']);
                            JointFollow::where(['id'=>$find['id']])->update(['staff_id'=>$v['id']]);
                            $model = \addons\qingdongams\model\Workorder::get($id);
                        }
                        unset($staff[$k]);
                    }
                }
                JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE,
                    'relation_id' => $id,
                    'roles' => 2
                ])->delete();

                $show_staff_id = [];
                $show_staff_id[] = $model->owner_staff_id;
                $jointFollow = new JointFollow();
                $add = [];
                $find = JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE,
                    'relation_id' => $id,
                    'roles' => 1
                ])->find();
                foreach ($staff as $v) {
                    if($v['id'] != $find['staff_id']) {
                        $add[] = [
                            'relation_type' => $jointFollow::WORKORDER_TYPE,
                            'relation_id' => $id,
                            'staff_id' => $v['id'],
                            'is_edit' => $v['is_edit'],
                            'roles' => 2,
                        ];
                        $show_staff_id[] = $v['id'];
                    }
                }
                $jointFollow->saveAll($add);
                $model->save(['show_staff_id' => implode(',', $show_staff_id)]);
                $this->success('编辑成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE, 'relation_id' => $ids,'roles' => 2])->with(['staff'])->select();
        $staffs = Staff::getList();
        $principal = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE, 'relation_id' => $ids,'roles' => 1])->with(['staff'])->find();
        $this->assign('staffs', $staffs);
        $this->assign('principal', $principal);
        $this->assign('id',$ids);
        $this->assign('list', $list);
        return $this->view->fetch();
    }

    public function add_team($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params['staff_id']) {
                $this->error('请选择员工');
            }
            if ($params['is_edit'] == '') {
                $this->error('请选择权限');
            }
            $is_have = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::WORKORDER_TYPE, 'relation_id' => $ids, 'staff_id' => $params['staff_id']])->with(['staff'])->select();
            if ($is_have) {
                $this->error('该员工已存在团队中');
            }
            $info = Staff::get($params['staff_id'])->toArray();
            $info['is_edit'] = $params['is_edit'];
            $this->success('添加成功', '', $info);
        }
        $staffs = Staff::getList();
        $this->assign('staffs', $staffs);
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }
}
